package com.joymart.admin.rest;


import com.joymart.common.error.handling.JoymartBusinessException;
import com.joymart.common.model.Range;
import com.joymart.common.utils.SecurityUtils;
import com.joymart.message.model.JoyMessage;
import com.joymart.message.service.JoyMessageService;
import com.joymart.message.service.JoyMessageService.JoyMessageDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;


@RestController
@RequestMapping("/admin")
public class JoyMessageAdminController {

    @Autowired
    private JoyMessageService joyMessageService;

    @GetMapping("/joyMessages/{channel}")
    private Page<?> search(@PathVariable String channel,
                           @RequestParam(required = false) Boolean replied,
                           @RequestParam LocalDateTime start,
                           @RequestParam LocalDateTime end,
                           @RequestParam(value = "pageNo", defaultValue = "0")Integer pageNo,
                           @RequestParam(value = "pageSize", defaultValue = "20")Integer pageSize){

        switch (channel){
            case "productConsult"-> SecurityUtils.requiresRestAuthority("ProductConsult");
            case "healthConsult"-> SecurityUtils.requiresRestAuthority("HealthConsult");
        }

        Range range = Range.of(start, end);
        Pageable pageable = PageRequest.of(pageNo, pageSize);
        return joyMessageService.search(channel, null, null, replied, range, pageable);

    }

    /**
     * 答复
     * @param
     * @return
     */
    @PutMapping("/joyMessages/{channel}/{id}")
    private JoyMessageDto replyMessage(@RequestBody Map<String,String> body,
                                       @PathVariable String channel,
                                       @PathVariable String id){
        switch (channel){
            case "productConsult"-> SecurityUtils.requiresRestAuthority("ProductConsult");
            case "healthConsult"-> SecurityUtils.requiresRestAuthority("HealthConsult");
        }
        String reply = body.get("reply");
        JoyMessage joyMessage = joyMessageService.findById(id);
        if(!joyMessage.getChannel().equals(channel)){
            throw new JoymartBusinessException("暂无数据权限");
        }
        joyMessageService.replyMessage(joyMessage, reply);
        return joyMessageService.toDto(joyMessage);
    }



}
